//
//  CommunityViewController.m
//  shusheng
//
//  Created by rimi on 16/7/9.
//  Copyright © 2016年 yuying. All rights reserved.
//

#import "CommunityViewController.h"
#import "CommunityTableViewCell.h"
#import "CellWithImages.h"
#import "DetailCommunityViewController.h"
#import "SendTieziViewController.h"
#import "SDAutoLayout.h"
#import "UIImageView+WebCache.h"
//#import "UITableView+SDAutoTableViewCellHeight.h"
//#import <UITableView+SDAutoTableViewCellHeight.h>
//#import <UITableView+SDAutoTableViewCellHeight.h>
//#import <SDAutoLayout.h>
//#import <SDAutoLayout/SDAutoLayout.h>
//#import "UIView+SDAutoLayout.h"

@interface CommunityViewController ()<UITableViewDataSource,UITableViewDelegate,AVIMClientDelegate,UIViewControllerTransitioningDelegate>
{
    NSInteger cellHeight;
}
@property (nonatomic,strong) UITableView *tableView;
@property (nonatomic,strong) UILabel *titleLbael;
@property (nonatomic,strong) UIButton *sendMessage;
@property (nonatomic,strong) NSArray *allTiezi;


@end

@implementation CommunityViewController






- (void)viewDidLoad {
    [super viewDidLoad];
    self.transitioningDelegate = self;
    self.modalPresentationStyle = UIModalPresentationCustom;
    [self.view addSubview:self.tableView];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view).with.offset(100);
        make.bottom.equalTo(self.view).with.offset(0);
        make.left.equalTo(self.view).with.offset(0);
        make.right.equalTo(self.view).with.offset(0);
    }];
    
    [self.view addSubview:self.titleLbael];
    [self.titleLbael mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.view).with.offset(BUTTON_HEIGHT);
            make.right.equalTo(self.view).with.offset(-100);
            make.left.equalTo(self.view).with.offset(100);
            make.height.offset(30);
        }];
    
    [self.view addSubview:self.sendMessage];
    [self.sendMessage mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view).with.offset(BUTTON_HEIGHT);
        make.right.equalTo(self.view).with.offset(-10);
        make.width.offset(50);
        make.height.offset(30);
    }];
    
    
    [self getTiezi];
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [self getTiezi];
    }];
    
 
   
}


-(void)endRefresh{
    [self.tableView.mj_header endRefreshing];

}


- (void)getTiezi{

    AVQuery *query = [AVQuery queryWithClassName:@"Tiezi"];
    [query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
        
        NSArray *arr = [[NSArray alloc] init];
        NSMutableArray *arry = [[NSMutableArray alloc] init];
        arr = objects;
        for (int i = arr.count-1; i > -1; i --) {
            [arry addObject:arr[i]];
        }
        
        
        self.allTiezi = arry;
        NSLog(@"%@",objects);
//        for (AVObject *todo in todos) {
//            todo[@"status"] = @1;
//        }
   
        [self endRefresh];
        [self.tableView reloadData];
        
       
    }];
}



- (IBAction)responBtn:(UIButton *)sender {
    NSLog(@"返回");
    [self dismissViewControllerAnimated:YES completion:nil];
}

#pragma make -- UIViewControllerTransitioningDelegate --
-(id<UIViewControllerAnimatedTransitioning>)animationControllerForPresentedController:(UIViewController *)presented presentingController:(UIViewController *)presenting sourceController:(UIViewController *)source{
    
    return [AnimatedTransitioning transitionWithTransitionType:CircleSpreadTransitionTypePresent];
}

-(id<UIViewControllerAnimatedTransitioning>)animationControllerForDismissedController:(UIViewController *)dismissed{
    return [AnimatedTransitioning transitionWithTransitionType:CircleSpreadTransitionTypeDismiss];
}
#pragma mark -- UITableViewDataSource && UITableViewDelegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.allTiezi.count;
}



-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return [self cellHeightForIndexPath:indexPath cellContentViewWidth:[UIScreen mainScreen].bounds.size.width tableView:tableView];
//   return [tableView cellHeightForIndexPath:indexPath cellContentViewWidth:[UIScreen mainScreen].bounds.size.width];
//    return cellHeight;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    
    CellWithImages *cell = [tableView dequeueReusableCellWithIdentifier:@"CellWithImages"];
    if (!cell) {
        cell = [[CellWithImages alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"CellWithImages"];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.articleName.text = self.allTiezi[indexPath.row][@"title"];
    cell.detailName.text = self.allTiezi[indexPath.row][@"content"];
    NSArray *arr = [[NSArray alloc] init];
    arr = self.allTiezi[indexPath.row][@"images"];
    if (arr.count == 0) {
            cell.imagesView1.hidden = YES;
        cell.imagesView1.sd_layout.autoHeightRatio(0);
        cell.imagesView2.hidden = YES;
        cell.imagesView3.hidden = YES;
    }else if (arr.count == 3){
        NSString *imageName = [NSString stringWithFormat:@"placehoder.png"];

        UIImage *image = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForAuxiliaryExecutable:imageName]];
        cell.imagesView1.hidden = NO;
        cell.imagesView1.sd_layout.autoHeightRatio(1);
        cell.imagesView2.hidden = NO;
        cell.imagesView3.hidden = NO;
        [cell.imagesView1 sd_setImageWithURL:arr[0] placeholderImage:image];
        [cell.imagesView2 sd_setImageWithURL:arr[1] placeholderImage:image];
        [cell.imagesView3 sd_setImageWithURL:arr[2] placeholderImage:image];
    } else if (arr.count == 1){
        NSString *imageName = [NSString stringWithFormat:@"placehoder.png"];
        
        UIImage *image = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForAuxiliaryExecutable:imageName]];
        cell.imagesView1.hidden = NO;
        cell.imagesView1.sd_layout.autoHeightRatio(1);
        cell.imagesView2.hidden = YES;
        cell.imagesView3.hidden = YES;
        [cell.imagesView1 sd_setImageWithURL:arr[0] placeholderImage:image];
    } else if (arr.count == 2){
        NSString *imageName = [NSString stringWithFormat:@"placehoder.png"];
        
        UIImage *image = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForAuxiliaryExecutable:imageName]];
        cell.imagesView1.hidden = NO;
        cell.imagesView1.sd_layout.autoHeightRatio(1);
        cell.imagesView2.hidden = NO;
        cell.imagesView3.hidden = YES;
        [cell.imagesView1 sd_setImageWithURL:arr[0] placeholderImage:image];
        [cell.imagesView2 sd_setImageWithURL:arr[1] placeholderImage:image];
       
    }
//    AVFile *file = [AVFile fileWithURL:self.allTiezi[0]];
//    [file getThumbnail:YES width:100 height:100 withBlock:^(UIImage *image, NSError *error) {
//    }];
    
//    cell.imagesView1.hidden = YES;
//    cell.imagesView1.sd_layout.autoHeightRatio(1);
//    cell.imagesView2.hidden = YES;
//    cell.imagesView3.hidden = YES;
//    UIImage *pic = cell.imagesView1.image;
//    if (pic.size.width > 0) {
//        CGFloat scale = pic.size.height / pic.size.width;
//        cell.imagesView1.sd_layout.autoHeightRatio(scale);
//        cell.imagesView1.image = pic;
//        
//        _view4.hidden = YES;
//    } else {
//        _view3.sd_layout.autoHeightRatio(0);
//        _view4.hidden = NO;
//    }
    
    //***********************高度自适应cell设置步骤************************
    
    
    
    
    
//    UITableViewCell *cell;
//    if (indexPath.row != indexPath.row) {
//        
//        cell = [tableView dequeueReusableCellWithIdentifier:@"CommunityTableViewCell"];
//        if (!cell) {
//            cell = [[CommunityTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"CommunityTableViewCell"];
//            
//        }
//        cellHeight = 120;
//       
//        
//        
//    }else{
//            cell = [tableView dequeueReusableCellWithIdentifier:@"CellWithImages"];
//            if (!cell) {
//                cell = [[CellWithImages alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"CellWithImages"];
//            }
//        
//            cellHeight = 250;
//    }
//    CommunityTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CommunityTableViewCell"];
//    if (!cell) {
//        cell = [[CommunityTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"CommunityTableViewCell"];
//        
//    }
//    cellHeight = 120;
//    cell.selectionStyle = UITableViewCellSelectionStyleNone;
//    cell.articleName.text = self.allTiezi[indexPath.row][@"title"];
//    cell.detailName.text = self.allTiezi[indexPath.row][@"content"];
//    
    NSDate* str = self.allTiezi[indexPath.row][@"createdAt"];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"hh:mm"];
    NSString *dateString = [dateFormatter stringFromDate:str];
    NSLog(@"dateString:%@",dateString);
    NSString *objectid = self.allTiezi[indexPath.row][@"author"][@"objectId"];
    AVQuery *query = [AVQuery queryWithClassName:@"_User"];
    [query getObjectInBackgroundWithId:objectid block:^(AVObject *object, NSError *error) {
//       cell.authorName.text = object[@"username"];
        cell.authorName.text = [object[@"username"] stringByAppendingString:@"  "];
        cell.authorName.text = [cell.authorName.text stringByAppendingString:dateString];
        
        
    }];
//
//    
//    
//    
//    
//        cell.detailName.text = self.allTiezi[indexPath.row][@"content"];
//    cell.articleName.text = self.allTiezi[indexPath.row][@"title"];
//
    [cell useCellFrameCacheWithIndexPath:indexPath tableView:tableView];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    DetailCommunityViewController *detail = [[DetailCommunityViewController alloc] init];
    detail.clientid = self.allTiezi[indexPath.row][@"objectId"];
    AVQuery *userQuery = [AVQuery queryWithClassName:@"_User"];
    [userQuery findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
        //        self.allTiezi = objects;
        NSArray *arr = objects;
        
        for (AVObject *todo in arr) {
          [detail.allUsers addObject:todo.objectId];
        }
        
    }];
    
    detail.headSource = self.allTiezi[indexPath.row];
   detail.currentObject = self.allTiezi[indexPath.row];
    [self addChildViewController:detail];
    [self.view addSubview:detail.view];
}



-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    editingStyle = UITableViewCellEditingStyleDelete;//此处的EditingStyle可等于任意UITableViewCellEditingStyle，该行代码只在iOS8.0以前版本有作用，也可以不实现。
}

- (NSArray<UITableViewRowAction *> *)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewRowAction *deleteRoWAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDestructive title:@"删除" handler:^(UITableViewRowAction *action, NSIndexPath *indexPath) {//title可自已定义
        [self deleteTiezi];
    }];//此处是iOS8.0以后苹果最新推出的api，UITableViewRowAction，Style是划出的标签颜色等状态的定义，这里也可自行定义
 
    return @[deleteRoWAction];//最后返回这俩个RowAction 的数组
    
}


- (void)deleteTiezi{
    NSLog(@"点击删除");
//    if ([AVUser currentUser].objectId == ) {
//        <#statements#>
//    }
}


#pragma mark --  Getter
- (UITableView *)tableView{
    if (!_tableView) {
        _tableView = [[UITableView alloc] init];
        _tableView.delegate = self;
        _tableView.dataSource = self;
//        _tableView.rowHeight = 120;
//        _tableView.rowHeight = 250;
        _tableView.estimatedRowHeight = 100;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
       
    }
    return _tableView;
}

- (UILabel *)titleLbael{
    if (!_titleLbael) {
        _titleLbael = [[UILabel alloc] init];
        _titleLbael.text = @"社区";
        _titleLbael.textAlignment = NSTextAlignmentCenter;
        //    titleLbael.backgroundColor = [UIColor orangeColor];
        _titleLbael.font = [UIFont systemFontOfSize:20];
    }
    return _titleLbael;
}

- (UIButton *)sendMessage{
    if (!_sendMessage) {
        _sendMessage = [[UIButton alloc] init];
        [_sendMessage setTitle:@"发帖" forState:UIControlStateNormal];
        _sendMessage.titleLabel.font = [UIFont systemFontOfSize:15];
        [_sendMessage addTarget:self action:@selector(respondsToSendMessage:) forControlEvents:UIControlEventTouchUpInside];
        [_sendMessage setTitleColor:FONT_COLOR forState:UIControlStateNormal];
    }
    return _sendMessage;
}

- (void)respondsToSendMessage:(UIButton *)sender{
    NSLog(@"发帖");
    SendTieziViewController *viewController = [[SendTieziViewController alloc] init];
    [self addChildViewController:viewController];
    [self.view addSubview:viewController.view];
}

- (NSArray *)allTiezi{
    if (!_allTiezi) {
        _allTiezi = [[NSArray alloc] init];
    }
    return _allTiezi;
}

@end
